<template>
<section>
    <!--工具条-->
    <Search :searchList="searchList" @search="search" ref="search">

    </Search>

    <ButtonBar :keyName="barKey" @callAction="callAction">

    </ButtonBar>
    <div class="table">

        <!--列表-->
        <el-table ref="singleTable" @select="select" :data="roles" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;" max-height="490" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
            <el-table-column type="selection">
            </el-table-column>
            <el-table-column type="index" label="列号" width="65">
            </el-table-column>
            <el-table-column prop="Name" label="角色名">
            </el-table-column>
            <el-table-column prop="Code" label="编码">
            </el-table-column>
            <el-table-column prop="OrderSort" label="排序">
            </el-table-column>
            <el-table-column prop="IsEnabled" label="状态" ilter-placement="bottom-end">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.IsEnabled ===true ? 'success' : 'danger'" disable-transitions>{{(scope.row.IsEnabled===true?'启用':'禁用')}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="CreateTime" label="创建时间" :formatter="formatTime">
            </el-table-column>
            <el-table-column prop="ModifiedTime" label="修改时间" :formatter="formatTime">
            </el-table-column>
            <el-table-column prop="Description" label="描述">
            </el-table-column>
        </el-table>
    </div>
    <el-col :span="24" class="paging">

        <el-pagination background layout="total,prev, pager, next" :page-size='pageSize' :total="total" :current-page="pageIndex" @current-change="currentChange" style="text-align:center;">
        </el-pagination>
    </el-col>
    <!-- <Paging :page-size='5' :total="total" @currentChange="currentChange"></Paging> -->

    <!--新增与修改界面-->
    <el-dialog :title="dialogTitle" :visible.sync="roleFormVisible" v-model="roleFormVisible" :close-on-click-modal="false" @close="close">
        <el-tabs type="border-card">

            <el-tab-pane label="角色基本信息">
                <el-form label-width="80px" :model="roleForm" :rules="formRules" ref="roleForm">
                    <el-form-item label="角色名称" prop="Name">
                        <el-input v-model="roleForm.Name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="编码" prop="Code">
                        <el-input v-model="roleForm.Code" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-radio-group v-model="roleForm.IsEnabled" prop="IsEnabled">
                            <el-radio class="radio" :label="true">启用</el-radio>
                            <el-radio class="radio" :label="false">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="描述">
                        <el-input type="textarea" v-model="roleForm.Description" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="角色资源授权">
                <el-form label-width="80px">
                    <el-tree :default-checked-keys="permissionIds" @check-change="handleMenuCheckChange" :check-strictly="true" :data="permissionTreeList" show-checkbox default-expand-all node-key="Id" ref="tree" :props="defaultProps" element-loading-text="拼命加载中">
                    </el-tree>
                </el-form>

            </el-tab-pane>

        </el-tabs>

        <div slot="footer" class="dialog-footer">
            <el-button @click.native="cancel">取消</el-button>
            <el-button type="primary" @click.native="submitForm" :loading="loading">提交</el-button>
        </div>
    </el-dialog>
    <!--工具条-->

</section>
</template>

<script>
import util from '../../common/js/util'
import Search from '@/views/Search.vue'
import ButtonBar from '@/components/ButtonBar'
import Paging from '@/components/Paging'
//import NProgress from 'nprogress'
import {
    getRoleListPage,
    addOrUpdateRoleAsync,
    loadRoleFormData,
    deleteRole,
    deleteUser,
    getPermissionList,

} from '../../api/api';
// import Search from '../Search';
export default {

    data() {
        return {

            defaultProps: {
                children: 'children',
                label: 'Name'
            },
            barKey: "角色列表",
            dialogTitle: "新增",
            searchList: [{

                value: "",
                name: "Name",
                title: "角色名",
                valueType: "",
            }, {

                value: "",
                name: "Code",
                title: "编码",
                valueType: "",
            }],
            total: 0,
            pageIndex: 1,
            pageSize: 10,
            loading: false,
            listLoading: false,
            roleFormVisible: false,
            selection: [],

            roleForm: { //表单数据
                Name: "",
                Code: "",
                IsEnabled: true,
                Id: "",
            },
            formRules: {

                Name: [

                    {
                        required: true,
                        message: '请输入角色名',
                        trigger: 'blur'
                    },
                    {
                        min: 1,
                        max: 10,
                        message: '长度在 1 到 10 个字符',
                        trigger: 'blur'
                    }
                ],
                Code: [

                    {
                        required: true,
                        message: '请输入编号',
                        trigger: 'blur'
                    },
                    {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur'
                    }
                ],
                IsEnabled: [

                    {
                        required: true,
                        message: '请选择状态',
                        trigger: 'blur'
                    },
                    {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur'
                    }
                ],
                Description: [

                    {
                        max: 10,
                        message: '长度在1000个字符',
                        trigger: 'blur'
                    }
                ]
            },
            isChangePage: false,
            // filters: [],
            roles: [],
            permissionTreeList: [],
            permissionIds: [],

        }
    },
    methods: {

        callAction: function (params) {

            util.callAction(this, params);
        },
        search: function (data) {

            this.getRoles(data);
        },
        //性别显示转换
        formatSex: function (row, column) {
            return row.Sex == 0 ? '男' : row.Sex == 1 ? '女' : '未知';
        },
        formatTime: function (row, column, cellValue, index) {
            var crtTime = new Date(cellValue);
            return this.dateFtt("yyyy-MM-dd hh:mm:ss", crtTime); //直接调用公共JS里面的时间类处理的办法     
        },

        dateFtt(fmt, date) { //author: meizz   
            var o = {
                "M+": date.getMonth() + 1, //月份   
                "d+": date.getDate(), //日   
                "h+": date.getHours(), //小时   
                "m+": date.getMinutes(), //分   
                "s+": date.getSeconds(), //秒   
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
                "S": date.getMilliseconds() //毫秒   
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        currentChange: function (row) {
            this.pageIndex = row;
            if (this.total > 1) {
                this.getRoles();
            }

            //
        },

        //获取用户列表
        getRoles(filters) {

            let newFilters = filters || [];
            let para = {

                pageSize: this.pageSize,
                filters: newFilters,
                pageIndex: newFilters.length > 0 ? 1 : this.pageIndex,
            };
            this.listLoading = true;
            //NProgress.start();
            getRoleListPage(para).then((res) => {

                this.total = res.data.total;
                this.roles = res.data.data;
                this.listLoading = false;
                //NProgress.done();
            });
        },
        getPermissions() {
            let para = {

                pageSize: 0,
                filters: [],
                pageIndex: 10,
            };
            getPermissionList(para).then((res) => {
                this.permissionTreeList = res.data;
            });
        },
        //删除

        //显示编辑界面

        //显示新增界面

        //编辑
        handleUpdate: function () {
            let _this = this;

            util.getSingleSelectionTableData(this.selection, function (id, row) {

                _this.dialogTitle = "修改";
                let para = {
                    id: id
                };

                loadRoleFormData(para).then(res => {

                    //this.userForm = Object.assign({}, row);
                    let {
                        message,
                        success,
                        type,
                        data
                    } = res;
                    if (res.success) {

                        _this.roleForm = data;

                        _this.permissionIds = res.data.PermissionIds;
                        _this.roleFormVisible = true;

                    }

                })
            });

        },
        //提交新增与修改数据
        submitForm: function () {
            this.$refs.roleForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.loading = true;
                        //NProgress.start();

                        let permissionIds = this.getCheckedKeys();
                        let para = Object.assign({}, this.roleForm);
                        para.PermissionIds = permissionIds;

                        addOrUpdateRoleAsync(para).then((res) => {

                            if (util.isEmt.format(res)) {
                                this.loading = false;
                                return;
                            }
                            if (res.success) {

                                this.loading = false;
                                //NProgress.done();
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                this.$refs['roleForm'].resetFields();
                                this.roleFormVisible = false;
                                // debugger;
                                // if (res.data.isRefresh == true) {
                                //     this.$store.commit("clearAllItem");
                                //     this.$router.push('/');
                                // }
                                this.getRoles();
                            } else {
                                this.loading = false;
                                this.$message({
                                    message: res.message,

                                    type: 'error'
                                });

                            }

                        });

                    });
                }
            });
        },
        //新增
        handleAdd: function () {
            this.dialogTitle = "新增";
            let para = {};
            this.roleFormVisible = true;

            this.roleForm = Object.assign({}, { //表单数据
                Name: "",
                Code: "",
                IsEnabled: true,

            });
            this.permissionIds = [];

            // loadRoleFormData(para).then(res => {
            //     this.roleFormVisible = true;

            //     let {
            //         message,
            //         success,
            //         type,
            //         data
            //     } = res;
            //     if (res.success) {
            //         debugger;
            //         this.roleForm = data;

            //     }

            // })
        },
        selsChange: function (sels) {
            this.sels = sels;
        },
        //表格选中
        select: function (selection, row) {

            this.selection = selection;
        },
        cancel: function () {
            this.roleFormVisible = false;

            // this.roleForm.IsEnabled = true;
            // this.roleForm.Description = "";
            this.$refs['roleForm'].resetFields();
            this.$refs.tree.setCheckedKeys([]);
        },
        handleDelete: function () {
            var _this = this;
            util.getSingleSelectionTableData(_this.selection, function (id, row) {
                if (row.Name == "管理员" && row.Code == "Admin") {
                    _this.$message({
                        message: '该用色拥有最高权限，不能删除！！！',
                        type: 'error'
                    });
                    return;
                }

                var para = {
                    id: id
                };

                _this.listLoading = true;

                deleteRole(para).then((res) => {
                    if (res.success) {

                        _this.$message({
                            message: res.message,
                            type: 'success'
                        });
                        _this.$refs.search.reset();
                        _this.getRoles();

                    } else {

                        _this.$message({
                            message: res.message,

                            type: 'error'
                        });
                    }

                });
                _this.listLoading = false;

            });
        },
        getCheckedKeys() {
            return this.$refs.tree.getCheckedKeys();
        },
        handleMenuCheckChange: function (data, check, subCheck) {

            if (check) {
                // 节点选中时同步选中父节点
                let parentId = data.ParentId
                if (parentId != null) {
                    this.$refs.tree.setChecked(parentId, true, false);
                }

            } else {
                // 节点取消选中时同步取消选中子节点
                if (data.children != null) {
                    if (data.children.length > 0) {
                        data.children.forEach(element => {
                            this.$refs.tree.setChecked(element.Id, false, false)
                        });
                    }
                }
            }
        },
        setCheckedKeys() {
            this.$refs.tree.setCheckedKeys([]);
            this.$refs.tree.setCheckedKeys(this.permissionIds);
        },
        close: function () {
            this.$refs.tree.setCheckedKeys([]);
        }

    },
    components: {
        Search,
        ButtonBar,
        Paging
    },
    mounted() {
        this.getRoles();
        this.getPermissions();

    }
}
</script>

<style scoped>

</style>
